package com.interview.ujiuye3;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyCache{
    private volatile Map<String,Object> map = new HashMap<>();
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    //写方法
    public void put(String key,Object object){
        readWriteLock.writeLock().lock();//获取写锁
        System.out.println(Thread.currentThread().getName() +"开始写入数据:" +  key);
        try { TimeUnit.MICROSECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
        map.put(key,object);
        System.out.println(Thread.currentThread().getName() +"完成写入数据:" +  key);
        readWriteLock.writeLock().unlock();//释放写锁
    }

    //读方法
    public void get(String key){
        readWriteLock.readLock().lock();
        System.out.println(Thread.currentThread().getName()+"开始读取数据:" + key);
        try { TimeUnit.MICROSECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName()+"结束读取数据->:" + o);
        readWriteLock.readLock().unlock();
    }
}



public class ReadWriterLockDemo {
    public static void main(String[] args) {
        MyCache cache = new MyCache();//创建缓存对象
        //五个线程写入数据
        for (int i=0; i<5; i++){
            final  int tempInt = i;
            new Thread(
                    ()-> {
                        cache.put(tempInt+"",tempInt+"");
                    },"线程"+tempInt
            ).start();
        }

        //五个线程读取数据
        for (int i=0; i<5; i++){
            final  int tempInt = i;
            new Thread(
                    ()-> {
                        cache.get(tempInt+"");
                    },"线程"+tempInt
            ).start();
        }
    }
}
